# -*- coding: utf-8 -*-
import netinfo
import mibinfo
from IPy import IP

# def discover(gateways):
#     '''discover with next hop'''
#     next_route =[]
#     dest = mibinfo.snmpwalk('.1.3.6.1.2.1.4.24.4.1.1', gateways) #ipRouteDest
#     mask = mibinfo.snmpwalk('.1.3.6.1.2.1.4.24.4.1.2', gateways)
#     next_hop = mibinfo.snmpwalk('.1.3.6.1.2.1.4.24.4.1.4', gateways) #ipRouteNextHop
#     ifindex = mibinfo.snmpwalk('.1.3.6.1.2.1.4.24.4.1.5', gateways)
#     type = mibinfo.snmpwalk('.1.3.6.1.2.1.4.24.4.1.6', gateways)
#     dev_info = mibinfo.snmp(gateways)
#     ipaddr = mibinfo.snmpwalk('.1.3.6.1.2.1.4.20.1.1', gateways)
#     ipnetmask = mibinfo.snmpwalk('.1.3.6.1.2.1.4.20.1.3', gateways)
#
#     if next_hop:
#         for item in next_hop:
#             if item != '0.0.0.0':
#                 discover(item)

def devtype(sysdesc):
    types ={'switch: CISCO C3560': 'C3560 Software',

           }
    for item in types:
        if types[item] in sysdesc:
            return item
    return sysdesc


def discover_arp(gateways, submask_list=[], devs_list=[], links=[]):
    '''discover with arp table'''

    try:
        dev_info = mibinfo.snmp(gateways)

    except BaseException as e:
        print(e)
        dev_info = mibinfo.snmp(gateways)

    if not dev_info[1]:
        print('Network erro!')
        return

    dev = {'type':devtype(dev_info[0])}
    dev['sysname'] = dev_info[1]
    dev['location'] = dev_info[2]
    dev['links'] = links
    ipent = mibinfo.snmpwalk('ipAdEntAddr', gateways)
    dev['ip'] = str(ipent)
    ipentmask = mibinfo.snmpwalk('ipAdEntNetMask', gateways)
    ipentindex = mibinfo.snmpwalk('ipAdEntIfIndex', gateways)
    iplist = zip(ipentindex, ipent, ipentmask)
    arpindex = mibinfo.snmpwalk('ipNetToMediaIfIndex', gateways)
    arptable = mibinfo.snmpwalk('ipNetToMediaNetAddress', gateways)
    arplist = zip(arpindex, arptable)
    arpdict ={}
    for arp in arplist:
        arp_index = arp[0]
        if arp_index not in arpdict:
            arpdict[arp_index] = [arp[1]]
        else:
            arpdict[arp_index].append(arp[1])

    # get checklist
    checklist = []
    for item in iplist:
        subnet = str(IP(item[1]).make_net(item[2]))
        if subnet not in submask_list:
            submask_list.append(subnet)
            arpent = arpdict[item[0]]
            if len(arpent) == 2:
                arpent.remove(item[1])
                checkip = arpent[0]
                checkinfo = mibinfo.snmp_check(checkip)
                if checkinfo[0] == 1:
                    dev['links'].append(checkinfo[0])
                    checklist.append(checkip)

    # insert devs_list
    devs_list.append(dev)
    print(devs_list)

    for item_check in checklist:
        discover_arp(gateways=item_check, submask_list=submask_list, devs_list=devs_list, links=dev_info[1])


def _main():
    gateways = netinfo.get_route()
    discover_arp(gateways)


if __name__ == '__main__':
    _main()
